package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.util.CheckPasswordUtils;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/6
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private static final String CURRENT_USER = "CURRENT_USER";
    @Autowired
    private UserService userService;
    @Autowired
    private RoleDao roleDao;

    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginParam param) {
        log.info("[登录]data:{}", param);
        //rpc调用查询用户信息
        User user = userService.findByUsername(param.getUsername());
        //用户不存在
        if (user == null) {
            log.info("[登录]失败，用户不存在！user:{}", param.getUsername());
            return new Result(false, MessageConst.LOGIN_FAIL + "，用户不存在！");
        }
        //密码不匹配登录失败
        boolean pswFlag = CheckPasswordUtils.checkPassword(param.password, user.getPassword());
        if (!pswFlag) {
            log.info("[登录]失败，密码不匹配");
            return new Result(false, MessageConst.LOGIN_FAIL + "密码不匹配！");
        }
        //用户登录成功
        log.info("[登录]成功，user:{}", user.getUsername());
        request.getSession().setAttribute("user", user);
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }

    /**
     * 添加用户，需要指定不同的角色，后续根据角色展示可以看到的页面
     * @param user
     * @return
     */
    @PostMapping("/addUser")
    @Transactional
    public Result addUser(@RequestBody User user){
        log.info("useruseruseruseruseruser:{}",user);
        //先添加，添加后带回来userid
        userService.addUser(user);
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            log.info("rolerolerolerolerolerolerole:{}",role.getName());
            //根据名字，查询角色对应的id
            List<Integer> roleIds = roleDao.selectRoleIdByName(role.getName());
            for (Integer roleId : roleIds) {
                //插入到角色和用户的关系表中
                roleDao.inserUserRoleByUserIdRoleId(user.getId(), roleId);
            }
        }

        return new Result(true,MessageConst.ADD_MEMBER_SUCCESS);

    }
}
